package com.studyroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.studyroom.dto.LoginDTO;
import com.studyroom.dto.RegisterDTO;
import com.studyroom.entity.User;
import com.studyroom.exception.ServiceException;
import com.studyroom.mapper.UserMapper;
import com.studyroom.service.UserService;
import com.studyroom.service.VerificationCodeService;
import com.studyroom.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private VerificationCodeService verificationCodeService;

    @Override
    public String login(LoginDTO loginDTO) {
        User user = getUserByUsername(loginDTO.getUsername());
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        
        // 直接比较明文密码
        if (!user.getPassword().equals(loginDTO.getPassword())) {
            throw new ServiceException("密码错误");
        }
        
        // 验证用户类型
        if (!user.getIsAdmin().equals(loginDTO.getIsAdmin())) {
            throw new ServiceException("用户类型不匹配，无权限登录");
        }
        
        return jwtTokenUtil.generateToken(user);
    }

    

    @Override
    public void register(RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (checkUsernameExists(registerDTO.getUsername())) {
            throw new ServiceException("用户名已存在");
        }

        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(registerDTO.getPassword());  // 直接存储明文密码
        user.setPhone(registerDTO.getPhone());
        user.setEmail(registerDTO.getEmail());
        user.setIsAdmin(registerDTO.getIsAdmin());
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        baseMapper.insert(user);
    }

    // 管理员添加用户的方法
    public void addUser(RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (checkUsernameExists(registerDTO.getUsername())) {
            throw new ServiceException("用户名已存在");
        }

        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(registerDTO.getPassword());  // 直接存储明文密码
        user.setPhone(registerDTO.getPhone());
        user.setEmail(registerDTO.getEmail());
        user.setIsAdmin(registerDTO.getIsAdmin());
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        baseMapper.insert(user);
    }

    @Override
    public User getUserByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.selectOne(queryWrapper);
    }

    private boolean checkUsernameExists(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public List<User> list() {
        return userMapper.selectAllUsers();  // 使用自定义查询
    }

    @Override
    public User findByUsernameAndPhone(String username, String phone) {
        return this.getOne(new LambdaQueryWrapper<User>()
            .eq(User::getUsername, username)
            .eq(User::getPhone, phone));
    }

    /**
     * 重置密码
     * @param username 用户名
     * @param email 邮箱
     * @param verificationCode 验证码
     * @param newPassword 新密码
     * @return 包含操作结果和消息的Map
     */
    @Transactional
    public Map<String, Object> resetPassword(String username, String email, String verificationCode, String newPassword) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        
        log.info("====== 开始重置密码流程 ======");
        log.info("参数: username={}, email={}, code={}, newPasswordLength={}", 
            username, email, verificationCode, newPassword != null ? newPassword.length() : 0);
        
        try {
            // 验证验证码
            log.info("正在验证验证码...");
            boolean verified = verificationCodeService.verifyCode(username, email, verificationCode);
            log.info("验证码验证结果: {}", verified);
            
            if (!verified) {
                log.warn("验证码无效或已过期");
                result.put("message", "验证码无效或已过期");
                return result;
            }
            
            // 查找用户
            log.info("正在查找用户: {}", username);
            User user = getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
            
            if (user == null) {
                log.warn("用户不存在: {}", username);
                result.put("message", "用户不存在");
                return result;
            }
            
            log.info("找到用户: id={}, username={}, email={}", user.getId(), user.getUsername(), user.getEmail());
            
            // 验证邮箱
            if (!email.equals(user.getEmail())) {
                log.warn("提供的邮箱({})与用户注册邮箱({})不匹配", email, user.getEmail());
                result.put("message", "邮箱与用户注册邮箱不匹配");
                return result;
            }
            
            // 更新密码 - 直接存储明文密码，与系统当前设计保持一致
            String oldPassword = user.getPassword();
            user.setPassword(newPassword);
            user.setUpdatedAt(LocalDateTime.now());
            
            log.info("正在更新用户密码: userId={}", user.getId());
            boolean updateResult = updateById(user);
            
            if (updateResult) {
                log.info("密码重置成功: userId={}", user.getId());
                result.put("success", true);
                result.put("message", "密码重置成功");
            } else {
                log.error("密码更新失败: userId={}", user.getId());
                // 恢复旧密码，避免出现异常后密码被修改
                user.setPassword(oldPassword);
                result.put("message", "密码更新失败");
            }
            
            log.info("====== 重置密码流程结束 ======");
            return result;
        } catch (Exception e) {
            log.error("重置密码过程中发生异常", e);
            log.info("====== 重置密码流程结束(异常) ======");
            result.put("message", "系统错误: " + e.getMessage());
            return result;
        }
    }
} 